package com.assignment.health.ui.qrcapture;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;

import androidx.activity.result.ActivityResultLauncher;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.assignment.health.LoginActivity;
import com.assignment.health.MainActivity;
import com.assignment.health.R;
import com.assignment.health.ScanActivity;
import com.google.gson.JsonObject;
import com.journeyapps.barcodescanner.CaptureManager;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;
import com.journeyapps.barcodescanner.ScanContract;
import com.journeyapps.barcodescanner.ScanOptions;
import com.net.http.NetClient;
import com.user.UserInformation;

import java.util.Objects;

import retrofit2.Retrofit;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link LocationQRCapture#newInstance} factory method to
 * create an instance of this fragment.
 */
public class LocationQRCapture extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private CaptureManager capture;
    private DecoratedBarcodeView barcodeScannerView;
    private Button scanButton;
    private String scanned_place;
    private Handler scanHandler;

    private final ActivityResultLauncher<ScanOptions> barcodeLauncher = registerForActivityResult(new ScanContract(),
            result -> {
                if(result.getContents() == null) {
                    Toast.makeText(getActivity(), "Cancelled", Toast.LENGTH_LONG).show();

                    scanButton.setEnabled(true);
                } else {
                    String place_name = result.getContents();
//                    scanned_place = place_name;
                    Toast.makeText(getActivity(), "Scanned: " + place_name, Toast.LENGTH_LONG).show();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            launchPost(place_name);
                        }
                    }).start();
                    scanButton.setEnabled(true);
                }
            });

    public LocationQRCapture() {
        // Required empty public constructor
    }
    @SuppressLint("HandlerLeak")
    private void setHandler() {
        scanHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0:
                        Toast.makeText(getActivity(), "Server has no response, Please wait a minute...", Toast.LENGTH_LONG).show();
                        break;
                    case 1:
                        Toast.makeText(getActivity(), "Sent successfully.", Toast.LENGTH_LONG).show();
                        break;
                    case 2:
                        Toast.makeText(getActivity(), "Failed: " + (String)msg.obj, Toast.LENGTH_LONG).show();
                        break;
                }
            }
        };
    }
    private void launchPost(String scanned_place) {
        System.out.println("HIHIHIHIHIHIHIHIH");
        System.out.println(UserInformation.token);
        System.out.println(scanned_place);
        if (UserInformation.available == 0) kickOut();
        else {
            JsonObject response = NetClient.AddPlace(UserInformation.token, scanned_place);
            if (response == null) {
//                Toast.makeText(getActivity(), "Server has no response, Please wait a minute...", Toast.LENGTH_LONG).show();
                scanHandler.sendMessage(scanHandler.obtainMessage(0));
                System.out.println("Server has no response, Please wait a minute...");
                return;
            }

            String status = response.get("status").getAsString();

            if (Objects.equals(status, "OK")) {
//                Toast.makeText(getActivity(), "Sent successfully.", Toast.LENGTH_LONG).show();
                scanHandler.sendMessage(scanHandler.obtainMessage(1));
                System.out.println("Success");
            } else {
//                Toast.makeText(getActivity(), "Failed: " + response.get("message").getAsString(), Toast.LENGTH_LONG).show();
                scanHandler.sendMessage(scanHandler.obtainMessage(2, response.get("message").getAsString()));
                System.out.println("Failed " + response.get("message").getAsString());
                if (Objects.equals(status, "TokenInvalid")) {
                    System.out.println("token invalid");
                    kickOut();
                }
            }
        }
    }

    private void kickOut() {
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        startActivity(intent);
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment LocationQRCapture.
     */
    // TODO: Rename and change types and number of parameters
    public static LocationQRCapture newInstance(String param1, String param2) {
        LocationQRCapture fragment = new LocationQRCapture();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_position_qr_capture, container, false);
        setHandler();
        scanButton = (Button)view.findViewById(R.id.scan_button);
        scanButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scanButton.setEnabled(false);
                ScanOptions options = new ScanOptions();
                options.setCaptureActivity(ScanActivity.class);
                options.setDesiredBarcodeFormats(ScanOptions.QR_CODE);
                options.setPrompt("Scan a QR code");
                options.setCameraId(0);  // Use a specific camera of the device
                options.setBeepEnabled(false);
                options.setBarcodeImageEnabled(true);
//                barcodeLauncher.launch(options);
                barcodeLauncher.launch(options);
            }
        });

        return view;
    }
}